package server

import (
	"strings"
	"wolongauth/database"
	"wolongauth/wolonghelp"

	"github.com/gofiber/fiber/v2"
)

func BindRoutes() {
	WebServer.Static("/", "./public")
	WebServer.Get("/", IndexRoute)
	WebServer.Get("/login", LoginRoute)
	WebServer.Get("/new", NewRoute)
}

func ErrHelperFunc(c *fiber.Ctx, err error) error {
	return c.JSON(fiber.Map{"code": 8000, "message": err.Error()})
}

func LoginRoute(c *fiber.Ctx) error {
	if c.Query("user", "") != "" && c.Query("password", "") != "" {
		user := strings.TrimSpace(c.Query("user"))
		password := strings.TrimSpace(c.Query("password"))
		s, err := SessionStore.Get(c)
		if err != nil {
			return c.JSON(fiber.Map{"code": 8000, "message": err.Error()})
		}
		if user == "" || password == "" {
			s.Set("errmsg", "账号或密码不能为空！")
			s.Save()
			return c.Redirect("/login")
		}
		loginok, err_login := database.Login(user, password)
		if loginok {
			s.Set("user", user)
			s.Set("password", password)
			s.Set("successmsg", "登录成功！")
			s.Save()
			return c.Redirect("/")
		}
		s.Set("errmsg", err_login.Error())
		s.Save()
		return c.Redirect("/login")
	}
	ShowMap := AddViewMap(c)
	return c.Render("login", ShowMap, "layout/main")
}

func IndexRoute(c *fiber.Ctx) error {
	ShowMap := AddViewMap(c)
	return c.Render("index", ShowMap, "layout/main")
}

func NewRoute(c *fiber.Ctx) error {
	ShowMap := AddViewMap(c)
	ShowMap["EnsureToKnow"] = wolonghelp.ReadEnsure()
	return c.Render("new", ShowMap, "layout/main")
}
